import { Icon, useCall, useToggle } from '@/components';
import { checkReturn, forkHandler } from '@/utils';
import { Button, Popover, Space } from 'antd';
import * as PropTypes from 'prop-types';
import React, { useEffect } from 'react';

function PopoverConfirm(props) {
  let {
    visible,
    beforeConfirm,
    onToggle,
    onOk,
    onCancel,
    okText = '确认',
    cancelText = '取消',
    content = '确认此操作吗?',
    hideActions = false,
    ...rest
  } = props;
  const [open, toggle] = useToggle(visible, onToggle);
  const [loading, toggleLoading] = useToggle();

  useEffect(() => {
    if (open && loading) toggleLoading();
  }, [open]);

  const handleVisibleChange = useCall(async (visi) => {
    if (visi && !(await checkReturn(beforeConfirm?.()))) return;
    if (!loading && visi !== open) toggle();
  });

  const handleOk = useCall(forkHandler(toggleLoading, onOk, toggle, toggleLoading, true).catch(toggleLoading));

  const handleCancel = useCall(forkHandler(() => !loading, onCancel, toggle, true));

  const renderContent =
    typeof content === 'function' ? (
      content({ visible: open, toggle, loading, onOk: handleOk, onCancel: handleCancel })
    ) : (
      <>
        <Icon type='ExclamationCircleFilled' className='c-warning' />
        &nbsp;&nbsp;
        {content}
      </>
    );

  if (!okText && !cancelText) {
    return (
      <Popover
        trigger='click'
        visible={open}
        {...rest}
        content={renderContent}
        handleVisibleChange={handleVisibleChange}
      />
    );
  }

  return (
    <Popover
      trigger='click'
      {...rest}
      visible={open}
      content={
        <>
          {renderContent}
          <div style={{ textAlign: 'right', display: 'block', marginTop: 12 }}>
            <Space size='small'>
              {okText && (
                <Button loading={loading} onClick={handleOk} type='primary' size='small'>
                  {okText}
                </Button>
              )}
              {cancelText && (
                <Button onClick={handleCancel} size='small'>
                  {cancelText}
                </Button>
              )}
            </Space>
          </div>
        </>
      }
      onVisibleChange={handleVisibleChange}
    />
  );
}

PopoverConfirm.propTypes = {
  visible: PropTypes.bool,
  onToggle: PropTypes.func,
  onOk: PropTypes.func,
  onCancel: PropTypes.func,
  okText: PropTypes.node,
  cancelText: PropTypes.node,
  content: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
};

export default PopoverConfirm;
